{% extends "base.html" %}

{% block content %}
<!-- 发布管理页面 -->
<div class="content-section">
    <div class="section-header">
        <h2 class="section-title">发布管理</h2>
        <div style="display: flex; gap: 10px;">
            <button class="btn btn-primary" onclick="testConnections()">测试连接</button>
            <button class="btn btn-primary" onclick="refreshRecords()">刷新</button>
        </div>
    </div>
    <div class="section-content">
        <!-- 平台状态 -->
        <div style="margin-bottom: 20px;">
            <h4>平台状态</h4>
            <div id="platformStatus" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 10px;">
                <!-- 平台状态将通过JavaScript加载 -->
            </div>
        </div>
        
        <!-- 筛选器 -->
        <div style="margin-bottom: 20px; display: flex; gap: 15px; align-items: center;">
            <label>平台：</label>
            <select id="platformFilter" onchange="filterRecords()">
                <option value="">全部</option>
                <option value="weibo">微博</option>
                <option value="twitter">Twitter</option>
                <option value="wechat">微信公众号</option>
            </select>
            
            <label>状态：</label>
            <select id="statusFilter" onchange="filterRecords()">
                <option value="">全部</option>
                <option value="success">成功</option>
                <option value="failed">失败</option>
                <option value="retry">重试中</option>
            </select>
        </div>

        <!-- 发布记录列表 -->
        <div id="recordsList">
            {% if records %}
            <ul class="item-list">
                {% for record in records %}
                <li class="item">
                    <div style="flex: 1;">
                        <div class="item-title">
                            内容ID: {{ record.content_id }}
                            {% if record.platform_post_id %}
                            | 平台ID: {{ record.platform_post_id }}
                            {% endif %}
                        </div>
                        <div class="item-meta">
                            平台: {{ record.platform }} | 
                            状态: {{ record.status }} | 
                            发布时间: {{ record.created_at.strftime('%Y-%m-%d %H:%M') }}
                            {% if record.updated_at and record.updated_at != record.created_at %}
                            | 更新时间: {{ record.updated_at.strftime('%Y-%m-%d %H:%M') }}
                            {% endif %}
                        </div>
                        {% if record.error_message %}
                        <div style="margin-top: 5px; color: #d32f2f; font-size: 0.9rem;">
                            错误: {{ record.error_message }}
                        </div>
                        {% endif %}
                    </div>
                    <div style="display: flex; flex-direction: column; gap: 5px; align-items: flex-end;">
                        {% if record.status == 'success' %}
                        <span class="badge badge-success">发布成功</span>
                        {% elif record.status == 'failed' %}
                        <span class="badge badge-error" style="background-color: #f8d7da; color: #721c24;">发布失败</span>
                        <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;" 
                                onclick="retryPublish({{ record.content_id }})">
                            重试
                        </button>
                        {% elif record.status == 'retry' %}
                        <span class="badge badge-warning">重试中</span>
                        {% endif %}
                        <span class="badge badge-info">{{ record.platform }}</span>
                        {% if record.platform_post_id and record.status == 'success' %}
                        <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;" 
                                onclick="viewPost('{{ record.platform }}', '{{ record.platform_post_id }}')">
                            查看
                        </button>
                        {% endif %}
                    </div>
                </li>
                {% endfor %}
            </ul>
            
            <!-- 统计信息 -->
            <div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
                <h4>发布统计</h4>
                <div id="publishStats" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-top: 10px;">
                    <!-- 统计信息将通过JavaScript加载 -->
                </div>
            </div>
            {% else %}
            <div class="empty-state">
                <p>暂无发布记录</p>
                <a href="/admin/contents" class="btn btn-primary">去发布内容</a>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 加载提示 -->
<div id="loadingModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 2rem; border-radius: 10px; text-align: center;">
        <div style="margin-bottom: 1rem;">⏳ 处理中...</div>
        <div id="loadingText">请稍候</div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadPlatformStatus();
    loadPublishStats();
});

async function testConnections() {
    showLoading('正在测试平台连接，请稍候...');
    
    try {
        const response = await fetch('/api/v1/publish/test-connections', {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            alert(`连接测试完成！\n连接成功: ${result.connected_platforms}/${result.total_platforms} 个平台`);
            loadPlatformStatus(); // 刷新平台状态
        } else {
            alert('连接测试失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        alert('连接测试失败：' + error.message);
    } finally {
        hideLoading();
    }
}

async function loadPlatformStatus() {
    try {
        const response = await fetch('/api/v1/publish/platforms');
        const result = await response.json();
        
        if (result.status === 'success') {
            const statusContainer = document.getElementById('platformStatus');
            statusContainer.innerHTML = '';
            
            result.platforms.forEach(platform => {
                const statusCard = document.createElement('div');
                statusCard.className = 'stat-card';
                statusCard.style.textAlign = 'center';
                
                const statusColor = platform.configured ? '#28a745' : '#ffc107';
                const statusText = platform.configured ? '已配置' : '模拟模式';
                
                statusCard.innerHTML = `
                    <div style="font-size: 1.2rem; font-weight: bold; margin-bottom: 0.5rem;">${platform.name}</div>
                    <div style="color: ${statusColor}; font-weight: bold;">${statusText}</div>
                    <div style="font-size: 0.9rem; color: #666; margin-top: 0.5rem;">${platform.status}</div>
                `;
                
                statusContainer.appendChild(statusCard);
            });
        }
    } catch (error) {
        console.error('加载平台状态失败:', error);
    }
}

async function loadPublishStats() {
    try {
        const response = await fetch('/api/v1/publish/records');
        const result = await response.json();
        
        if (result.status === 'success') {
            const records = result.data;
            const stats = {
                total: records.length,
                success: records.filter(r => r.status === 'success').length,
                failed: records.filter(r => r.status === 'failed').length,
                retry: records.filter(r => r.status === 'retry').length
            };
            
            const statsContainer = document.getElementById('publishStats');
            statsContainer.innerHTML = `
                <div style="text-align: center;">
                    <div style="font-size: 1.5rem; font-weight: bold; color: #333;">${stats.total}</div>
                    <div style="color: #666;">总发布次数</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 1.5rem; font-weight: bold; color: #28a745;">${stats.success}</div>
                    <div style="color: #666;">成功</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 1.5rem; font-weight: bold; color: #dc3545;">${stats.failed}</div>
                    <div style="color: #666;">失败</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 1.5rem; font-weight: bold; color: #ffc107;">${stats.retry}</div>
                    <div style="color: #666;">重试中</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 1.5rem; font-weight: bold; color: #17a2b8;">
                        ${stats.total > 0 ? Math.round(stats.success / stats.total * 100) : 0}%
                    </div>
                    <div style="color: #666;">成功率</div>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载发布统计失败:', error);
    }
}

async function retryPublish(contentId) {
    if (!confirm('确定要重试发布这个内容吗？')) {
        return;
    }
    
    showLoading('正在重试发布，请稍候...');
    
    try {
        const response = await fetch('/api/v1/publish/publish', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content_ids: [contentId]
            })
        });
        
        const result = await response.json();
        
        if (result.status === 'completed') {
            alert('重试发布完成！');
            location.reload();
        } else {
            alert('重试发布失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        alert('重试发布失败：' + error.message);
    } finally {
        hideLoading();
    }
}

function viewPost(platform, postId) {
    let url = '';
    
    switch (platform) {
        case 'weibo':
            url = `https://weibo.com/detail/${postId}`;
            break;
        case 'twitter':
            url = `https://twitter.com/user/status/${postId}`;
            break;
        case 'wechat':
            alert('微信公众号内容需要在微信公众号后台查看');
            return;
        default:
            alert('不支持的平台');
            return;
    }
    
    window.open(url, '_blank');
}

function refreshRecords() {
    location.reload();
}

function filterRecords() {
    const platformFilter = document.getElementById('platformFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;
    
    let url = '/admin/publish?';
    if (platformFilter) url += `platform=${platformFilter}&`;
    if (statusFilter) url += `status=${statusFilter}&`;
    
    window.location.href = url;
}

function showLoading(text) {
    document.getElementById('loadingText').textContent = text;
    document.getElementById('loadingModal').style.display = 'block';
}

function hideLoading() {
    document.getElementById('loadingModal').style.display = 'none';
}
</script>
{% endblock %}